import { get, post } from '@common/ajax';
import { SHOP_URL, MARKET_URL } from '@common/url';
import { MARKET_ISSUER, MARKET_DISTRIBUTE_SCENE } from '@constants/market';
import logger from '@common/logger';

import {
    GET_GOODS_DETAIL_INFO,
    SET_SELECT_SKU_INFO,
    GET_GOODS_DISCOUNT_INFO,
    SET_DETAIL_STORE_INFO,
} from '../mutationType';
import { dealDiscountInfo } from '@biztools/detail';
import { TipError, TipSuccess } from '@common/tip';

const detail = {
    state: {
        goodsDetail: null,
        activityList: [],
        couponList: [],
        selectSkuInfo: null,
        storeInfo: null,
    },
    mutations: {
        GET_GOODS_DETAIL_INFO: (state, goodsDetail) => {
            Object.assign(state, { goodsDetail });
        },
        SET_SELECT_SKU_INFO: (state, selectSkuInfo) => {
            Object.assign(state, { selectSkuInfo });
        },
        GET_GOODS_DISCOUNT_INFO: (state, { activityList, couponList }) => {
            Object.assign(state, { activityList, couponList });
        },
        SET_DETAIL_STORE_INFO: (state, storeInfo) => {
            Object.assign(state, { storeInfo });
        },
    },
    actions: {
        // 获取商品详情
        getGoodsDetailInfo: async ({ commit }, goodsId) => {
            const res = await get(SHOP_URL.goodsDetail, {
                prod_id: goodsId,
            });
            logger.success('Detail => 商品详情', res);
            commit(GET_GOODS_DETAIL_INFO, res);
        },
        // 设置选中的规格
        setSelectSkuInfo: ({ commit }, skuInfo) => {
            logger.info('Detail => 选中规格', skuInfo);
            commit(SET_SELECT_SKU_INFO, skuInfo);
        },
        // 获取商品可用的优惠信息-促销 & 优惠券
        getGoodsDiscountInfo: async ({ commit }, goodsId) => {
            const res = await get(MARKET_URL.discount, {
                owner_id: 0,
                issuer: MARKET_ISSUER.emall,
                item_id: goodsId,
            });
            const { activityList, couponList } = dealDiscountInfo(res.data.offers);
            logger.debugger('Detail => 获取的活动和优惠券为：', activityList, couponList);
            commit(GET_GOODS_DISCOUNT_INFO, {
                activityList,
                couponList,
            });
        },
        // 领取优惠券
        getDetailCoupon: async ({ commit }, couponId) => {
            const res = await post(MARKET_URL.getCoupon(couponId), {
                got_issuer: MARKET_ISSUER.emall,
                got_scene: MARKET_DISTRIBUTE_SCENE.public,
            });
            logger.success('Detail => 领取优惠券结果', res);
            return res.success ? TipSuccess('领取成功') : TipError(res.msg);
        },
        setDetailStoreInfo: async ({ commit }, storeInfo) => {
            commit(SET_DETAIL_STORE_INFO, storeInfo);
        },
    },
};

export default detail;
